package com.zhm.demo.ws.simple;

import cn.hutool.core.text.AntPathMatcher;
import com.zhm.demo.ws.bean.Shout;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.*;

@Controller
public class MyHandler implements WebSocketHandler {


    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;


    @MessageMapping("/send/{userId}")
    public void handleShout(@Payload Shout incoming, @DestinationVariable String userId) {
        System.out.println("userId " + userId);
        System.out.println("Received message:" + incoming.getMessage());
        simpMessagingTemplate.convertAndSend("/user/1/a", "测试SimpMessageSendingOperations ");
    }

    @SubscribeMapping("/rpc")
    public Shout handleSubscribe() {
        Shout outing = new Shout();
        outing.setMessage("subscribes");
        return outing;
    }


    // 连接继开处理
    @Override
    public void afterConnectionClosed(WebSocketSession arg0, CloseStatus arg1) throws Exception {
        // TODO Auto-generated method stub

        System.out.println("Connection closed..." + arg0.getRemoteAddress().toString());

    }

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    // 连接建立处理
    @Override
    public void afterConnectionEstablished(WebSocketSession arg0) throws Exception {
        // TODO Auto-generated method stub
//        PathPattern pattern = PathPatternParser.defaultInstance.parse("/{type}/{userId}");
//        // 提取匹配到的的变量值
//        System.out.println("是否匹配：" + pattern.matches(PathContainer.parsePath(arg0.getUri().getPath())));
//        PathPattern.PathMatchInfo pathMatchInfo = pattern.matchAndExtract(PathContainer.parsePath(arg0.getUri().getPath()));
//        System.out.println("匹配到的值情况：" + pathMatchInfo.getUriVariables());
//        Map<String, String> uriVariables = pathMatchInfo.getUriVariables();
//        String type = uriVariables.get("type");
//        String userId = uriVariables.get("userId");
        System.out.println("Connection established..." + arg0.getUri().getPath());
        System.out.println("Connection established..." + arg0.getRemoteAddress().toString());
    }

    // 接收、发送信息处理
    @Override
    public void handleMessage(WebSocketSession arg0, WebSocketMessage<?> arg1) throws Exception {
        // TODO Auto-generated method stub
        try {
            System.out.println("Req: " + arg1.getPayload());
            // 发送信息
            TextMessage returnMessage = new TextMessage(arg1.getPayload() + " received at server");
            arg0.sendMessage(returnMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 错误处理（客户端突然关闭等接收到的错误）
    @Override
    public void handleTransportError(WebSocketSession arg0, Throwable arg1) throws Exception {
        // TODO Auto-generated method stub
        if (arg0.isOpen()) {
            arg0.close();
        }
        System.out.println(arg1.toString());
        System.out.println("WS connection error,close...");
    }

    @Override
    public boolean supportsPartialMessages() {
        // TODO Auto-generated method stub
        return false;
    }
}
